package com.snailwu.ratelimiter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RateLimiterApplication implements ApplicationRunner {

    private final Logger log = LoggerFactory.getLogger(RateLimiterApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(RateLimiterApplication.class, args);
    }

    private final ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Resource(name = "demoRateLimiter")
    private RedisRateLimiter rateLimiter;

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        f1();
        f2();
    }

    private void f1() {
        while (true) {
            if (!rateLimiter.tryAcquire()) {
                continue;
            }
            log.info("获取令牌，成功！");
        }
    }

    private void f2() {
        for (int i = 0; i < 10; i++) {
            executorService.submit(() -> {
                while (true) {
                    if (!rateLimiter.tryAcquire()) {
                        continue;
                    }
                    log.info("获取令牌，成功！");
                }
            });
        }
    }
}
